const { Report, User, Job } = require("../model");

// 改
exports.updateReport = async (req, res, next) => {
  try {
    const fun = await Report.findByIdAndUpdate(req.params.id, {
      $set: req.body
    })
    if (fun) {
      res.status(200).json({
        code: 200,
        msg: "success",
      });
    } else {
      res.status(200).json({
        code: 500,
        msg: "修改失败",
      });
    }
    
  } catch (error) {
    next(error);
  }
};

// 查
exports.getReport = async (req, res, next) => {
  try {
    // 模糊查询
    // find({name:/程序员/}) 
    const items = await Report.find();
    let data = []
    for (let i = 0;i < items.length;i++) {
      const v = items[i]
      let obj = {}
      obj.content = v.content
      obj.status = v.status
      obj._id = v._id
      const userInfo = await User.findById(v.userId)
      obj.userInfo = userInfo
      
      const jobInfo = await Job.findById(v.jobId)
      obj.jobInfo = jobInfo
      if (jobInfo) {
        const publishInfo = await User.findById(jobInfo.publisherId)
        obj.publishInfo = publishInfo
      }
      data.push(obj)
      console.log(data)
    }
    console.log(2)
    res.status(200).json({
      code: 200,
      data
    });
  } catch (error) {
    next(error);
  }
};
// 增
exports.addReport = async (req, res, next) => {
  try {
    const model = new Report(req.body);
    await model.save();
    res.status(200).json({
      code: 200,
      msg: "success",
    });
  } catch (error) {
    next(error);
  }
};
// 删
exports.deleteReport = async (req, res, next) => {
  try {
    const rs = await Report.findByIdAndDelete(req.params.id)
    if (rs) {
      res.status(200).json({
        code: 200,
        msg: '删除成功'
      });
    }
  } catch (error) {
    next(error);
  }
};

